package com.algorithm.example.stack;

import java.util.Iterator;

/**
 * <p>
 * 数组堆
 * </p>
 *
 * @author lzt
 * @version 1.0
 * @since 2024/1/26 12:38
 */
public class ArrayStack<E> implements Stack<E>, Iterable<E> {
    private final E[] array;

    private int top;

    public ArrayStack(int array) {
        this.array = (E[]) new Object[array];
    }

    @Override
    public boolean push(E value) {
        if (isFull()) {
            return false;
        }
        array[top] = value;
        top++;
        return true;
    }

    @Override
    public E pop() {
        if (isEmpty()) {
            return null;
        }
        return array[--top];
    }

    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        return array[top - 1];
    }

    @Override
    public boolean isEmpty() {
        return top == 0;
    }

    @Override
    public boolean isFull() {
        return top == array.length;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            int p = 0;
            @Override
            public boolean hasNext() {
                return p != top;
            }

            @Override
            public E next() {
                E e = array[p];
                p++;
                return e;
            }
        };
    }
}
